package com.chenyi.leetcode.editor.cn;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author by chenyi
 * @className TwoSum
 * @date 2022-04-05 22:17:02
 */
public class TwoSum {
    public static void main(String[] args) {
        Solution solution = new TwoSum().new Solution();
        int[] arr = {1, 2, 3, 5};
        System.out.println(Arrays.toString(solution.twoSum(arr, 8)));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    @SuppressWarnings("AlibabaCommentsMustBeJavadocFormat")
    class Solution {
        public int[] twoSum(int[] nums, int target) {
            // O(n2)时间复杂度，比较两个值相加是否相等
//            for (int i = 0; i < nums.length; i++) {
//                for (int j = 1; j < nums.length; j++) {
//                    if (i != j && nums[i] + nums[j] == target) {
//                        return new int[]{i, j};
//                    }
//                }
//            }
//            return null;
            Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
            for (int i = 0; i < nums.length; ++i) {
                if (hashtable.containsKey(target - nums[i])) {
                    return new int[]{hashtable.get(target - nums[i]), i};
                }
                hashtable.put(nums[i], i);
            }
            return new int[0];
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
